# Copyright (c) 2025, EAM Team and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
import qrcode
from io import BytesIO
import base64
import json


class Equipment(Document):
    def autoname(self):
        """自动生成设备编码"""
        if not self.equipment_code:
            # 获取设备分类的代码前缀
            category = frappe.get_doc("Equipment Category", self.equipment_category) if self.equipment_category else None
            prefix = category.code_prefix if category and hasattr(category, 'code_prefix') else "EQ"
            
            # 生成序号
            last_equipment = frappe.get_all("Equipment", 
                filters={"equipment_code": ["like", f"{prefix}%"]},
                fields=["equipment_code"],
                order_by="creation desc",
                limit=1
            )
            
            if last_equipment:
                last_code = last_equipment[0].equipment_code
                try:
                    last_num = int(last_code.split("-")[-1])
                    new_num = last_num + 1
                except:
                    new_num = 1
            else:
                new_num = 1
            
            self.equipment_code = f"{prefix}-{new_num:04d}"
        
        self.name = self.equipment_code

    def validate(self):
        """验证数据"""
        # 计算保修到期日
        if self.purchase_date and self.warranty_period:
            from frappe.utils import add_months
            self.warranty_end_date = add_months(self.purchase_date, self.warranty_period)

    def after_insert(self):
        """设备创建后自动生成二维码"""
        self.generate_qr_code()
        self.create_equipment_history("采购入库", "设备档案创建")

    def generate_qr_code(self):
        """生成设备二维码"""
        try:
            # 创建二维码内容
            qr_data = {
                "equipment_code": self.equipment_code,
                "equipment_name": self.equipment_name,
                "doctype": "Equipment",
                "name": self.name,
                "url": f"/app/equipment/{self.name}"
            }
            
            # 生成二维码
            qr = qrcode.QRCode(version=1, box_size=10, border=5)
            qr.add_data(json.dumps(qr_data))
            qr.make(fit=True)
            
            # 创建二维码图片
            img = qr.make_image(fill_color="black", back_color="white")
            
            # 转换为base64
            buffer = BytesIO()
            img.save(buffer, format='PNG')
            img_str = base64.b64encode(buffer.getvalue()).decode()
            
            # 保存到设备记录
            file_doc = frappe.get_doc({
                "doctype": "File",
                "file_name": f"qr_code_{self.equipment_code}.png",
                "content": img_str,
                "decode": True,
                "attached_to_doctype": "Equipment",
                "attached_to_name": self.name,
                "is_private": 0
            })
            file_doc.insert()
            
            self.qr_code = file_doc.file_url
            self.save()
            
        except Exception as e:
            frappe.log_error(f"生成二维码失败: {str(e)}", "Equipment QR Code Generation")

    def create_equipment_history(self, record_type, description, cost=0):
        """创建设备履历记录"""
        try:
            history = frappe.get_doc({
                "doctype": "Equipment History",
                "equipment": self.name,
                "record_type": record_type,
                "description": description,
                "operator": frappe.session.user,
                "cost": cost,
                "record_date": frappe.utils.now()
            })
            history.insert()
        except Exception as e:
            frappe.log_error(f"创建设备履历失败: {str(e)}", "Equipment History Creation")

    def update_maintenance_cost(self, cost):
        """更新累计维护成本"""
        self.total_maintenance_cost = (self.total_maintenance_cost or 0) + cost
        self.save()

    def update_status(self, new_status, reason=""):
        """更新设备状态并记录履历"""
        old_status = self.status
        self.status = new_status
        self.save()
        
        # 记录状态变更履历
        description = f"设备状态从 '{old_status}' 变更为 '{new_status}'"
        if reason:
            description += f"，原因：{reason}"
        
        self.create_equipment_history("状态变更", description)